<template>
  <div id="contentBox">
    <div class="listHead">
      <el-form>
        <el-input
          v-model="listForm.name"
          clearable
          placeholder="请输入活动名称"
          clear="cancelChoose"
          @keyup.enter.native="getList"
          @change="handleStatus"
        ></el-input>
        <el-select
          v-model="listForm.activity"
          clearable
          placeholder="全部活动"
          @change="handleActivity"
          @clear="cancelChoose"
        >
          <el-option label="拼团活动" value="1"></el-option>
          <!-- <el-option label="秒杀活动" value="2"></el-option> -->
        </el-select>
        <el-select v-model="listForm.status" clearable placeholder="全部状态" @change="handleStatus">
          <el-option label="进行中" value="2"></el-option>
          <el-option label="未开始" value="1"></el-option>
          <el-option label="已结束" value="3"></el-option>
        </el-select>
        <el-button type="primary" @click="getList">查询</el-button>
      </el-form>
      <div>
        <!-- <el-button type="primary" @click="$router.push('/marketing/group/add')">创建拼团</el-button> -->
        <el-button type="primary" @click="addGroupList">创建拼团</el-button>
        <!-- <el-button type="primary" @click="$router.push('/marketing/template/templateCenter')">海报模板中心</el-button> -->
      </div>
    </div>
    <el-table
      :data="listData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="655"
      max-height="660"
      :element-loading-text="global.loadingStr"
      :header-cell-style="{background:global.mainColor}"
    >
      <el-table-column type="index" label="序号" align="center">
        <template></template>
      </el-table-column>
      <el-table-column prop="activity" label="活动类型" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.activityType==1?'拼团活动':"秒杀活动"}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="activity" label="活动名称" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="courseName" label="课程名称" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.courseName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="活动时间" align="center" min-width="160px">
        <template slot-scope="scope">
          <span>{{ scope.row.activityStartTime | parseTime('{y}-{m}-{d}') }}至{{scope.row.activityEndTime | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="count" label="参与人数" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.partakeCount==null?'0':scope.row.partakeCount}} | {{scope.row.groupCount}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="拼团价格" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.groupPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="deposit" label="拼团定金" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.deposit==0?'-':scope.row.deposit}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status===2">进行中</span>
          <span v-else-if="scope.row.status===1">未开始</span>
          <span v-else-if="scope.row.status===3">已结束</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200px">
        <template slot-scope="{row,$index}">
          <el-button
            size="mini"
            type="success"
            v-if="row.status !== 3 && row.upDownShelves == 0"
            @click="handleUp(row)"
          >上架</el-button>
          <el-button
            size="mini"
            type="primary"
            v-if="row.partakeCount==0 && row.upDownShelves == 1"
            @click="handleDown(row)"
          >下架</el-button>
          <el-button
            size="mini"
            type="info"
            v-if="row.status !== 3 && row.partakeCount == 0"
            @click="handleEdit(row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="warning"
            v-if="row.status!==1"
            @click="handleDataInfo(row)"
          >统计</el-button>
          <el-button
            size="mini"
            type="danger"
            v-if="row.status===3 || row.status===1"
            @click="handleDelete(row,$index)"
          >删除</el-button>
          <el-button
            v-if="row.status!==3"
            size="mini"
            type="success"
            @click="generatePoster(row)"
          >生成海报</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listForm.currentPage"
      :limit.sync="listForm.pageSize"
      @pagination="getList"
    />
    <!-- 创建拼团 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialogVisible"
      width="700px"
      @close="$refs['form'].clearValidate()"
      @opened="$refs['form'].clearValidate()"
    >
      <el-form :model="form" :rules="formRules" ref="form" label-width="140px" class="demo-form">
        <el-form-item label="活动类型选择" prop="activityType">
          <el-select v-model="form.activityType" placeholder="请选择活动类型">
            <el-option label="拼团活动" value="1"></el-option>
            <!-- <el-option label="秒杀活动" value="2"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="活动标签" prop="activityLabelIds" class="activLabel">
          <el-radio-group v-model="form.activityLabelIds" @change="handleLabelName">
            <el-radio
              :label="item.id"
              v-for="(item,index) in labelList"
              :key="index"
            >{{item.labelName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课程选择" prop="courseId">
          <el-select
            v-model="form.courseId"
            placeholder="请选择课程"
            @change="hancldeChooseCourseList"
            no-data-text="无上架课程"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in courseList"
              :picker-options="pickerOptions"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程套餐" prop="setMealId" v-if="isShow">
          <el-radio-group v-model="form.setMealId" @change="handleMeal">
            <el-radio :label="item.id" v-for="(item,index) in mealList" :key="index">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="活动时间"> -->
        <el-form-item prop="activityStartTime" label="活动开始时间">
          <el-date-picker
            style="width:200px!important"
            type="date"
            placeholder="选择开始时间"
            v-model="form.activityStartTime"
            :picker-options="pickerOptions"
            @change="startDateChange"
          ></el-date-picker>
        </el-form-item>
        <!-- <span style="margin:0 15px">至</span> -->
        <el-form-item prop="activityEndTime" label="活动结束时间">
          <el-date-picker
            style="width:200px!important"
            type="date"
            placeholder="选择结束时间"
            v-model="form.activityEndTime"
            :picker-options="pickerOptions"
            @change="endDateChange"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-date-picker
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="dateLimitChange"
        ></el-date-picker>-->
        <!-- </el-form-item> -->
        <el-form-item label="拼团人数" prop="groupCount">
          <el-input v-model="form.groupCount" placeholder="请输入拼团人数"></el-input>
        </el-form-item>
        <el-form-item label="成团人数" prop="subgroupCount">
          <el-input v-model="form.subgroupCount" placeholder="请输入成团人数" :disabled='isEditSubgroupCount'></el-input>
        </el-form-item>
        <el-form-item label="拼团价格" prop="groupPrice">
          <el-input v-model="form.groupPrice" placeholder="请输入拼团价格"></el-input>
        </el-form-item>
        <el-form-item label="是否支持支付定金" prop="isDeposit">
          <el-radio-group v-model="form.isDeposit" @change="isShouldDeposite">
            <el-radio label="0">不支持</el-radio>
            <el-radio label="1">支持</el-radio>
          </el-radio-group>
          <el-tooltip class="item" placement="top">
            <div slot="content">
              <span>支持：可以设置定金金额，拼团成功后进行尾款支付</span>
              <br />
              <span>不支持：以拼团的价格进行拼团，一次性支付</span>
            </div>
            <el-button type="text" style=" margin-left:10px;">
              <i class="el-icon-question" style="font-size:16px"></i>
            </el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="拼团定金" prop="deposit" v-if="isDepositeShow">
          <el-input v-model="form.deposit" :disabled="isCanDeposit" placeholder="请输入拼团的定金"></el-input>
        </el-form-item>
        <!-- prop="validTime" -->
        <el-form-item label="成团有效时间" prop="validTime">
          <el-radio-group v-model="form.validTime" @change="settingTime">
            <el-radio label="24">24小时</el-radio>
            <el-radio label="36">36小时</el-radio>
            <el-radio label="48">48小时</el-radio>
            <el-radio :label="zero">自定义时间</el-radio>
          </el-radio-group>
          <el-input
            v-model="settime"
            placeholder="/小时"
            style="width:75px!important"
            @change="autoTime"
            :disabled="isCanInput"
          ></el-input>
          <el-tooltip class="item" placement="top">
            <div slot="content">
              <span>以团长发起的时间为准，机构可以设置24/36/48小时/自定义天数</span>
            </div>
            <el-button type="text" style="margin-left:10px;">
              <i class="el-icon-question" style="font-size:16px"></i>
            </el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="是否支持虚拟团" prop="isVirtualGroup">
          <el-radio-group v-model="form.isVirtualGroup" @change="isChooseVirtua">
            <el-radio label="0">不支持</el-radio>
            <el-radio label="1">支持</el-radio>
          </el-radio-group>
          <el-tooltip class="item" placement="top">
            <div slot="content">
              <span>支持：设置一些团长，营造一些气氛</span>
              <br />
              <span>不支持：只能由用户来发起团长</span>
            </div>
            <el-button type="text" style=" margin-left:10px;">
              <i class="el-icon-question" style="font-size:16px"></i>
            </el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="虚拟团设置" prop="virtualGroupCount" v-if="isVirtualShow">
          <el-input placeholder="请设置团个数" v-model="form.virtualGroupCount" class="settingLong"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="submitForm('form')">{{btnworld}}</el-button>
          <el-button @click="addDialogVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 生成海报 -->
    <el-dialog title="海报预览" :visible.sync="posterDialog" width="800px">
      <div class="canvas" ref="imageDom">
        <div class="canvas-box">
          <img class="canvas-bg" crossorigin="Anonymous" src="@/assets/images/组 36@2x.png" alt />
          <div class="avatr">
            <img :src="logo" alt />
          </div>
          <div class="name">
            <div>{{currentRow.businessName}}</div>
          </div>
          <div class="course-img">
            <img :src="courseImg" alt />
          </div>
          <div class="price">
            <span>￥</span>
            <span>{{currentRow.groupPrice}}</span>
            <div class="org">￥{{currentRow.setMealPrice}}</div>
            <div class="info">
              <p class="info-one">
                仅剩
                <span>{{currentRow.groupCount-currentRow.partakeCount||0}}个</span>名额啦
              </p>
              <p class="info-two">赶紧一起来拼团开课吧！</p>
            </div>
          </div>
          <div class="qrcode">
            <img crossorigin="Anonymous" :src="qrcode" alt />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="posterDialog = false">取 消</el-button>
        <el-button type="primary" @click="downloadPoster">下 载</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import { randomString } from "@/utils";

import * as Group from "@/api/group";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
export default {
  name: "GroupList",
  components: { Pagination },
  data() {
    var groupCount = (rule, value, callback) => {
      if (+value <= 0) {
        callback(new Error("拼团人数必须大于1"));
      } else if (value == "") {
        callback(new Error("请输入拼团人数"));
      } else {
        callback();
      }
    };
    // 成团人数
    var groupPeople = (rule, value, callback) => {
      if (this.form.groupCount == "") {
        callback(new Error("请填写拼团人数"));
        return;
      }
      if (+value > this.form.groupCount) {
        callback(new Error("成团人数不能大于拼团人数"));
        return;
      }
      if (+value <= 1) {
        callback(new Error("成团人数必须大于1"));
      } else if (value == "") {
        callback(new Error("请输入成团人数"));
      } else {
        callback();
      }
    };
    // 拼团价格
    var groupPrice = (rule, value, callback) => {
      console.log(value);
      if (value == "0" || value == "0.0" || value == "0.") {
        callback(new Error("拼团价格必须大于0"));
      }
      if (value == "") {
        callback(new Error("拼团价格不能为空"));
      }
      if (this.price == "") {
        callback(new Error("请先选择课程套餐"));
        return;
      }
      if (value > 0.01) {
        this.isCanDeposit = false;
      } else if (value <= 0.01 && this.form.isDeposit == "1") {
        this.form.deposit = 0.01;
        this.isCanDeposit = true;
        callback();
      }
      if (+value <= 0) {
        callback(new Error("拼团价格必须大于0"));
      } else if (value == "") {
        callback(new Error("请输入拼团价格"));
      } else if (+value > +this.price) {
        callback(new Error("拼团价格不能大于套餐原价" + this.price));
      } else {
        this.orgPrice = value;
        this.tenP = value * 0.1;
        this.threeP = value * 0.3;
        callback();
      }
    };
    // 拼团定金
    var deposite = (rule, value, callback) => {
      console.log(value);
      if (this.tenP == "" && this.threeP == "") {
        callback(new Error("请先选择拼团价格"));
        return;
      }
      if (
        (this.tenP < 0.01 && this.tenP !== "") ||
        (this.threeP < 0.01 && this.threeP !== "")
      ) {
        this.form.deposit = 0.01;
        this.isCanDeposit = true;
        callback();
        return;
      }
      if (this.form.deposit < 0.01 && this.form.isDeposit == "1") {
        callback(new Error("定金不能为空并且不能小于0.01"));
      }
      if (value < +this.tenP.toFixed(2) || value > this.threeP) {
        callback(
          new Error(
            `定金需要在${this.tenP.toFixed(2)}和${this.threeP.toFixed(2)}之间`
          )
        );
      }
      if (value == "") {
        callback(new Error("请输入拼团定金"));
      } else if (+value <= 0) {
        callback(new Error("拼团定金必须大于1"));
      } else {
        callback();
      }
    };
    // 虚拟团
    var fakegroup = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入虚拟团设置"));
      } else if (+value <= 0) {
        callback(new Error("虚拟团必须大于1"));
      } else {
        callback();
      }
    };
    return {
      posterDialog: false,
      logo: "",
      courseImg: "",
      qrcode: "",
      currentRow: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - 3600 * 1000 * 24;
        },
      },
      listForm: {
        currentPage: 1,
        pageSize: 10,
        name: "",
        status: null,
        activity: null,
        upDownShelves: "",
        delFlag: 0,
        activityType: null,
        businessId: localStorage.getItem("businessId"),
      },
      listData: [],
      total: 0,
      btnworld: "立刻创建",
      // 创建编辑
      title: "创建拼团",
      addDialogVisible: false,
      businessId: localStorage.getItem("businessId"),
      businessName: localStorage.getItem("businessName"),
      labelList: [], // 标签
      courseList: [], // 课程
      mealList: [], // 课程套餐
      groupId: null, // 拼团活动id
      isShow: false, // 是否展示课程套餐
      isDepositeShow: false, // 是否支持定金
      isVirtualShow: false, // 是否支持虚拟团
      isCanInput: false, // 自定义时间是否可输入
      isCanDeposit: "", // 拼团定金是否可输入
      settime: "", // 自定义成团有效时间
      needTime: "", // 最终成团时间
      value1: null,
      formRules: {
        activityType: [
          { required: true, message: "请选择活动类型", trigger: "change" },
        ],
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字", trigger: "blur" },
        ],
        courseId: [
          { required: true, message: "请选择课程", trigger: "change" },
        ],
        activityLabelIds: [
          { required: true, message: "请选择活动标签", trigger: "change" },
        ],
        setMealId: [
          { required: true, message: "请选择课程套餐", trigger: "change" },
        ],
        activityStartTime: [
          {
            required: true,
            message: "请选择开始日期",
            trigger: "change",
          },
        ],
        activityEndTime: [
          {
            required: true,
            message: "请选择结束日期",
            trigger: "change",
          },
        ],
        groupCount: [{ required: true, validator: groupCount }],
        subgroupCount: [{ required: true, validator: groupPeople }],
        groupPrice: [{ required: true, validator: groupPrice }],
        isDeposit: [
          { required: true, message: "是否支持支付定金", trigger: "change" },
        ],
        deposit: [{ validator: deposite, trigger: "change" }],
        validTime: [
          {
            required: true,
            message: "请选择或自定义成团有效时间",
            trigger: "change",
          },
        ],
        isVirtualGroup: [
          { required: true, message: "是否支持虚拟团", trigger: "change" },
        ],
        virtualGroupCount: [{ validator: fakegroup, trigger: "change" }],
      },
      form: {
        activityType: "", // 活动类型
        name: "", // 活动名称
        activityLabelNames: "", // 活动标签名字
        activityLabelIds: "", // 活动标签编号
        courseId: "", // 课程编号
        courseName: "", // 课程名字
        setMealId: "", // 套餐编号
        setMealName: "", // 套餐名称
        setMealPrice: "", // 套餐价格
        activityStartTime: "", // 起始时间
        activityEndTime: "", // 结束时间
        groupCount: "", // 拼团人数
        subgroupCount: "", // 成团人数
        groupPrice: "", // 拼团价格
        isDeposit: "", // 是否支持定金
        deposit: "", // 定金金额
        validTime: "", // 成团有效时间
        isVirtualGroup: "", // 虚拟团
        virtualGroupCount: "", // 虚拟团设置
        remark: "", // 备注
        upDownShelves: 1, // 上下架状态
        delFlag: 0, // 删除状态
      },
      price: "", // 成团原价格
      orgPrice: "", // 拼团价格
      tenP: "", // 10%
      threeP: "", // 30%
      zero: "",
      isEditSubgroupCount:false
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    getList() {
      Group.getGroupList(this.listForm).then((res) => {
        this.listData = res.data.records;
        this.total = res.data.total;
      });
    },
    // 自定义成团有效时间
    settingTime(e) {
      console.log(e);
      if (e == "24" || e == "36" || e == "48") {
        this.isCanInput = true;
        this.settime = "";
        this.formRules.validTime[0].required = true;
        this.needTime = e;
      } else if (e !== "24" || e !== "36" || e !== "48") {
        this.isCanInput = false;
        this.formRules.validTime[0].required = false;
      }
    },
    // 自定义时间
    autoTime(e) {
      console.log(e);
      console.log(this.form.validTime);
      // this.needTime = this.settime
      if (e == "0") {
        this.$message.error("成团有效期不能小于1小时");
        this.needTime = this.settime
      } else {
        this.needTime = e;
      }
    },
    // 提交
    submitForm(formName) {
      TDAPP.onEvent(`成团${this.needTime}小时`)
      this.form.deposit === 1 ? TDAPP.onEvent('拼团支持支付定金') : TDAPP.onEvent('拼团不支持支付定金')
      this.form.isVirtualGroup === 1 ? TDAPP.onEvent('支持虚拟团') : TDAPP.onEvent('不支持虚拟团')
      if (this.form.activityStartTime > this.form.activityEndTime) {
        this.$message.error("结束日期必须在开始日期之后");
        return;
      }
      if (+this.needTime >= 168 ) {
        this.$message.error("成团有效期不能超过1周");
        return;
      } else if (+this.needTime < 1 ) {
        this.$message.error("成团有效期不能小于1小时");
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "创建拼团") {
            Group.addNewGroup({
              businessId: this.businessId,
              businessName: this.businessName,
              activityType: Number(this.form.activityType),
              name: this.form.name,
              activityLabelNames: this.form.activityLabelNames,
              activityLabelIds: this.form.activityLabelIds,
              courseId: this.form.courseId,
              courseName: this.form.courseName,
              setMealId: this.form.setMealId,
              setMealName: this.form.setMealName,
              setMealPrice: Number(this.form.setMealPrice),
              activityStartTime: this.form.activityStartTime,
              activityEndTime: Number(this.form.activityEndTime),
              groupCount: Number(this.form.groupCount),
              subgroupCount: Number(this.form.subgroupCount),
              groupPrice: Number(this.form.groupPrice),
              isDeposit: Number(this.form.isDeposit),
              deposit: Number(this.form.deposit),
              validTime: this.needTime * 60 * 60 * 1000,
              isVirtualGroup: Number(this.form.isVirtualGroup),
              virtualGroupCount: Number(this.form.virtualGroupCount),
              remark: this.form.remark,
              upDownShelves: 1, // 上下架状态
              delFlag: 0, // 删除状态
            }).then((res) => {
              if (res.code == "200") {
                this.$message.success("创建成功");
                this.$refs["form"].resetFields();
                this.form.remark = "";
                this.addDialogVisible = false;
                this.getList();
              }
            });
          } else {
            Group.editGroupList({
              id: this.groupId,
              businessId: this.businessId,
              businessName: this.form.businessName,
              activityType: Number(this.form.activityType),
              name: this.form.name,
              activityLabelNames: this.form.activityLabelNames,
              activityLabelIds: this.form.activityLabelIds,
              courseId: this.form.courseId,
              courseName: this.form.courseName,
              setMealId: this.form.setMealId,
              setMealName: this.form.setMealName,
              setMealPrice: Number(this.form.setMealPrice),
              activityStartTime: this.form.activityStartTime,
              activityEndTime: Number(this.form.activityEndTime),
              groupCount: Number(this.form.groupCount),
              subgroupCount: Number(this.form.subgroupCount),
              groupPrice: Number(this.form.groupPrice),
              isDeposit: Number(this.form.isDeposit),
              deposit: Number(this.form.deposit),
              validTime: this.needTime * 60 * 60 * 1000,
              isVirtualGroup: Number(this.form.isVirtualGroup),
              virtualGroupCount: Number(this.form.virtualGroupCount),
              remark: this.form.remark,
              upDownShelves: 1, // 上下架状态
              delFlag: 0, // 删除状态
            }).then((res) => {
              if (res.code === "200") {
                this.$message.success("编辑成功");
                this.addDialogVisible = false;
                this.$refs.form.resetFields();
                this.getList();
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除
    handleDelete(row, $index) {
      this.$confirm("此操作将永久删除该活动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        Group.delGroupList({
          id: row.id,
        }).then((res) => {
          if (res.code === "200") {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.listData.splice($index, 1);
            this.getList();
          }
        });
      });
    },
    // 生成海报
    generatePoster(row) {
      TDAPP.onEvent('生成海报')
      this.currentRow = row;
      const imgUrl = row.courseAvatar.split(",")[0];
      this.getImgBase64(imgUrl);
      this.getImgLogoBase64();
      // console.log(this.getImgBase64(row.courseAvatar))
      Group.QRcode({
        id: row.courseId,
        str: row.id + "I2",
        pagesPath: `pages/groupCourse/groupCourse`,
      }).then((res) => {
        const { data } = res;
        if (data instanceof Object) {
          this.qrcode = data.qrcodeImg;
        } else {
          this.qrcode = data;
        }
      });
      this.posterDialog = true;
    },
    // 调用具体转换的方法
    getBase64Images(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      // var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
      var dataURL = canvas.toDataURL("image/");
      return dataURL;
    },
    /* oss图片转base64*/
    getImgBase64(imgurl) {
      const that = this;
      var img = new Image();
      img.setAttribute("crossOrigin", "anonymous");
      // img.src = imgurl + '?v=any_string_is_ok' + Math.random()
      img.src = imgurl + "?v=any_string_is_ok";
      img.onload = function () {
        that.courseImg = that.getBase64Images(img);
      };
    },
    /* logo图片转base64*/
    getImgLogoBase64() {
      const that = this;
      const logoUrl = this.$store.getters.avatar;
      var img = new Image();
      img.setAttribute("crossOrigin", "anonymous");
      // img.src = imgurl + '?v=any_string_is_ok' + Math.random()
      img.src = logoUrl + "?v=any_string_is_ok";
      img.onload = function () {
        that.logo = that.getBase64Images(img);
      };
    },
    downloadPoster() {
      window.scrollTo(0, 0)
      const loading = this.$loading({
        lock: true,
        text: "努力生成中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        // this.$refs[formName].resetFields()
        const canvasBox = this.$refs.imageDom;
        // const canvasBox= cloneDom.cloneNode(true);
        // document.body.appendChild(canvasBox)
        this.$nextTick(() => {
          // 手动创建一个 canvas 标签
          const canvas = document.createElement("canvas");
          // 获取父标签，意思是这个标签内的 DOM 元素生成图片
          // 获取父级的宽高
          const width = parseInt(window.getComputedStyle(canvasBox).width);
          const height = parseInt(window.getComputedStyle(canvasBox).height);

          // let {width, height} = canvasBox.getBoundingClientRect();
          const dpr = window.devicePixelRatio || 1;
          // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
          canvas.width = width * dpr;
          canvas.height = height * dpr;
          canvas.style.width = width + "px";
          canvas.style.height = height + "px";
          const context = canvas.getContext("2d");
          context.scale(dpr, dpr);
          const rectObject = canvasBox.getBoundingClientRect();
          const eleft = rectObject.left;
          const etop = rectObject.top;
          context.translate(-eleft, -etop);
          // const sidebarStatus = Cookies.get('sidebarStatus') === '0' ? 2 : 5
          html2canvas(canvasBox, {
            useCORS: true, // 【重要】开启跨域配置
            allowTaint: true, // 允许跨域图片
            tainttest: true, // 检测每张图片都已经加载完成
            logging: false,
            ...canvas,
            // scrollY: 0,
            // scrollX: 0,
            letterRendering: true,
            backgroundColor: null, // null 表示设置背景为透明色
          }).then((canvas) => {
            // 转成图片，生成图片地址
            loading.close();
            const imgUrl = canvas.toDataURL("image/png");
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = imgUrl;
            link.download = `拼团活动海报_${randomString(3)}`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            // document.body.removeChild(canvasBox)
            // console.log(imgUrl)
          });
        });
      }, 500);
    },
    // 编辑
    handleEdit(row) {
      this.getLabelList(); // 获取标签页
      this.getCouseList(this.businessId); // 获取课程
      this.addDialogVisible = true;
      this.title = "编辑拼团";
      this.btnworld = "确认编辑";
      this.groupId = row.id;
      this.isEditSubgroupCount=true
      Group.checkGroupList({ id: row.id }).then((res) => {
        console.log(res.data);
        this.hancldeChooseCourseList(res.data.courseId);
        this.form = res.data;
        const courseIdcopy = res.data.courseId;
        this.form.courseId = res.data.courseId;
        this.form.activityType = res.data.activityType.toString();
        this.form.isDeposit = res.data.isDeposit.toString();
        this.form.isVirtualGroup = res.data.isVirtualGroup.toString();
        this.needTime = res.data.validTime / 60 / 60 / 1000;
        this.settime = res.data.validTime;
        this.orgPrice = res.data.groupPrice;
        this.price = res.data.setMealPrice;
        this.tenP = res.data.groupPrice * 0.1;
        this.threeP = res.data.groupPrice * 0.3;
        if (res.data.deposit <= 0.01 && res.data.isDeposit == "1") {
          this.form.deposit = 0.01;
          this.isCanDeposit = true;
        } else {
          this.isCanDeposit = false;
        }
        if (res.data.isVirtualGroup == "0") {
          this.isVirtualShow = false;
        } else {
          this.isVirtualShow = true;
        }
        if (res.data.isDeposit == "1") {
          this.isDepositeShow = true;
        } else {
          this.isDepositeShow = false;
        }
        this.form.validTime = (res.data.validTime / 60 / 60 / 1000).toString();
        if (
          res.data.validTime !== "24" &&
          res.data.validTime !== "36" &&
          res.data.validTime !== "48"
        ) {
          this.settime = res.data.validTime;
          this.zero = res.data.validTime;
          this.isCanInput = false;
        } else {
          this.zero = "";
          this.settime = "";
          this.isCanInput = true;
          this.form.validTime = res.data.validTime;
        }
        this.getMealList(courseIdcopy);
        this.getCouseList(this.businessId);
      });
    },
    // 创建
    addGroupList() {
      this.getLabelList(); // 获取标签页
      this.getCouseList(this.businessId); // 获取课程
      this.title = "创建拼团";
      this.btnworld = "立刻创建";
      this.addDialogVisible = true;
      this.isShow = false; //
      this.isDepositeShow = false;
      this.isVirtualShow = false;
      this.isCanInput = false;
      this.isCanDeposit = false;
      this.isEditSubgroupCount=false
      for (const key in this.form) {
        this.form[key] = "";
      }
      this.form.isVirtualGroup = "0"; // 是否虚拟团
      this.form.isDeposit = "0"; // 是否支付定金
      this.form.delFla = 0; // 删除状态
      this.settime = "";
      this.form.validTime = "24";
      // this.needTime=this.form.validTime* 60 * 60 * 1000
    },
    // 上架
    handleUp(row) {
      this.$confirm("是否确认上架该活动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        Group.upOrDownGroupList({
          id: row.id,
          upDownShelves: 1,
        }).then((res) => {
          if (res.code === "200") {
            this.$message({
              type: "success",
              message: "上架成功!",
            });
            this.getList();
          }
        });
      });
    },
    // 下架
    handleDown(row) {
      this.$confirm("是否确认下架该活动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        Group.upOrDownGroupList({
          id: row.id,
          upDownShelves: 0,
        }).then((res) => {
          if (res.code === "200") {
            this.$message({
              type: "success",
              message: "下架成功!",
            });
            this.getList();
          }
        });
      });
    },
    handleDataInfo(row) {
      TDAPP.onEvent('查看拼团统计')
      console.log(row);
      this.$router.push({
        path: "/marketing/group/dataInfo",
        query: {
          id: row.id,
        },
      });
    },
    // 拼团类型查询
    handleActivity(e) {
      this.listForm.activityType = Number(e);
      this.listForm.currentPage = 1;
      this.getList();
    },
    // 拼团状态查询
    handleStatus() {
      this.listForm.currentPage = 1;
      this.getList();
    },
    // 清除内容查询
    cancelChoose() {
      this.listForm.activityType = null;
      this.listForm.currentPage = 1;
      this.getList();
    },
    // 是否支持支付定金
    isShouldDeposite(value) {
      // console.log(value);
      if (value === "1") {
        this.isDepositeShow = true;
        this.formRules.deposit[0].required = true;
        this.form.deposit = "";
      } else {
        this.isDepositeShow = false;
        this.formRules.deposit[0].required = false;
        this.form.deposit = "";
      }
    },
    // 是否支持虚拟团
    isChooseVirtua(value) {
      // console.log(value);
      if (value === "0") {
        this.isVirtualShow = false;
        this.formRules.virtualGroupCount[0].required = false;
        this.form.virtualGroupCount = "";
      } else {
        this.isVirtualShow = true;
        this.formRules.virtualGroupCount[0].required = true;
        this.form.virtualGroupCount = "";
      }
    },
    // 获取标签
    getLabelList() {
      Group.getLabelList().then((res) => {
        this.labelList = res.data;
      });
    },
    // 查询课程
    getCouseList(businessId) {
      Group.getCourseList({ businessId }).then((res) => {
        this.courseList = res.data;
      });
    },
    // 查询套餐
    getMealList(courseId) {
      return new Promise((resolve, reject) => {
        Group.getMealList({ courseId }).then((res) => {
          this.mealList = res.data;
          resolve(res.data);
        });
      });
    },
    // },
    // 选择课程chang后立即更新课程套餐
    hancldeChooseCourseList(courseId) {
      // 课程名字
      this.courseList.forEach((item) => {
        if (item.id == courseId) {
          console.log(item.name);
          this.form.courseName = item.name;
          this.form.setMealName = item.name;
        }
      });
      this.form.setMealId = "";
      this.isShow = true;
      this.getMealList(courseId).then((res) => {});
    },
    // 存标签中文名
    handleLabelName(value) {
      this.labelList.forEach((item) => {
        if (item.id == value) {
          this.form.activityLabelNames = item.labelName;
        }
      });
    },
    // 存套餐中文名
    handleMeal(value) {
      this.mealList.forEach((item) => {
        if (item.id == value) {
          this.form.setMealName = item.name;
          this.form.setMealPrice = item.price;
          // this.form.courseName = item.name;
          this.price = item.price;
        }
      });
      console.log(this.form.setMealName);
    },
    // 开始日期转时间戳
    startDateChange(e) {
      this.form.activityStartTime = this.changTimeOut(e);
      console.log(this.form.activityStartTime);
    },
    // 结束日期转时间戳
    endDateChange(e) {
      this.form.activityEndTime =
        this.changTimeOut(e) + 24 * 60 * 60 * 1000 - 1;
      console.log(this.form.activityEndTime);
    },
    // 日期转换时间戳 2020-08-21  至 2020-08-25 + 23点59分59秒
    changTimeOut(e) {
      var dateTime = new Date(e);
      var resDate =
        dateTime.getFullYear() +
        "-" +
        (dateTime.getMonth() + 1) +
        "-" +
        dateTime.getDate() +
        " " +
        dateTime.getHours() +
        ":" +
        dateTime.getMinutes() +
        ":" +
        dateTime.getSeconds();
      const c = new Date(resDate).getTime();
      return c;
    },
  },
};
</script>

<style lang='scss' scoped>
#contentBox {
  padding: 20px;
  .listHead {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    .el-input {
      width: 200px;
    }
  }
  /deep/ .el-table--medium {
    height: 600px !important;
  }
  /deep/.el-form-item--medium {
    margin-bottom: 25px;
  }
  /deep/ .activLabel .el-radio-group {
    width: 70%;
  }
  /deep/ .activLabel .el-radio {
    margin: 10px;
  }
}
.canvas-box {
  position: relative;
  width: 750px;
  height: 1200px;
  // border: 1px solid #ccc;
  .canvas-bg {
    z-index: 1;
    position: absolute;
    top: 0;
    width: 100%;
    // height: 100%;
  }
  .avatr {
    z-index: 2;
    position: absolute;
    left: 295px;
    top: 38px;
    width: 165px;
    height: 165px;
    // border: 1px solid #ccc;
    border-radius: 50%;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .name {
    z-index: 2;
    position: absolute;
    // left: 312px;
    top: 180px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    > div {
      padding: 10px 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      min-width: 126px;
      font-size: 22px;
      font-family: PingFang SC;
      font-weight: 800;
      color: #ff5079;
      background: #ffffff;
      border-radius: 20px;
    }
  }
  .course-img {
    z-index: 2;
    position: absolute;
    left: 55px;
    top: 483px;
    width: 634px;
    height: 399px;
    border-radius: 20px;
    overflow: hidden;
    // border: 1px solid #ccc;
    > img {
      width: 100%;
      height: 100%;
    }
  }
  .price {
    z-index: 2;
    position: absolute;
    left: 55px;
    top: 913px;
    font-size: 48px;
    font-family: SF UI Display;
    font-weight: bold;
    color: #ff6a5d;
    > span:first-child {
      font-size: 36px;
      font-weight: 800;
    }
    .org {
      margin-left: 10px;
      font-size: 22px;
      font-family: SF UI Display;
      font-weight: bold;
      color: #b4b4b4;
      text-decoration: line-through;
    }
    .info {
      margin-top: 30px;
      font-size: 22px;
      letter-spacing: 3px;
      > p {
        margin: 0;
        font-family: PingFang SC;
        font-weight: 600;
        color: #333333;
      }
      .info-one {
        margin-bottom: 10px;
        > span {
          color: #ff6a5d;
        }
      }
    }
  }
  .qrcode {
    z-index: 2;
    position: absolute;
    left: 469px;
    top: 913px;
    width: 192px;
    height: 192px;
    border-radius: 50%;
    // border: 1px solid #ccc;
    overflow: hidden;
    > img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
